<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="UTF-8" />
    <title>Offer</title>
    <script
      crossorigin
      src="https://unpkg.com/react@16/umd/react.development.js"
    ></script>
    <script
      crossorigin
      src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"
    ></script>
    <script
      crossorigin
      src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.34/browser.min.js"
    ></script>
    <script src="https://cdn.jsdelivr.net/npm/babel-regenerator-runtime@6.5.0/runtime.min.js"></script>
  </head>
  <body>
    <div class="main">
      <div class="section" id="app1"></div>
    </div>
    <script type="text/babel">
      let rtc;
      const App = () => {
        const [log, setLog] = React.useState([]);

        React.useEffect(() => {
          (async () => {
            const socket = new WebSocket("ws://localhost:8888");
            await new Promise((r) => socket.addEventListener("open", r));

            const peer = (rtc = new RTCPeerConnection({
              iceServers: [{ urls: "stun:stun.l.google.com:19302" }],
            }));
            peer.onicecandidate = ({ candidate }) => {
              if (!candidate) {
                socket.send(JSON.stringify(peer.localDescription));
              }
            };

            const channel = peer.createDataChannel("chat");
            channel.onmessage = (ev) => {
              const text = new TextDecoder("utf-8").decode(ev.data);
              console.log(text);
              setLog((prev) => [...prev, text]);
            };

            let index = 0;
            channel.onopen = () => {
              console.log("open");
              setInterval(() => {
                if (index < 3) channel.send("ping" + index++);
                if (index === 3) {
                  peer.close();
                  index++;
                }
              }, 1000);
            };
            channel.onclose = (e) => {
              console.log("close", e);
            };
            channel.onerror = (e) => {
              console.log("error", e);
            };

            await new Promise((r) => (peer.onnegotiationneeded = r));

            const offer = await peer.createOffer();
            await peer.setLocalDescription(offer);

            socket.addEventListener("message", async (ev) => {
              const answer = JSON.parse(ev.data);
              console.log(answer.sdp);
              await peer.setRemoteDescription(answer);
            });
          })();
        }, []);

        return (
          <div>
            offer
            <div>
              {log.slice(-10).map((v, i) => (
                <div key={i}>{v}</div>
              ))}
            </div>
          </div>
        );
      };

      ReactDOM.render(<App />, document.getElementById("app1"));
    </script>
  </body>
</html>
